from django.shortcuts import render


# Create your views here.
from drf_haystack.viewsets import HaystackViewSet

from goods.models import SKU
from rest_framework import filters
from rest_framework.response import Response

from .serializers import SKUIndexSerializer
from rest_framework.generics import GenericAPIView
from rest_framework.generics import ListAPIView
from .serializers import HotSKUListSerializer, SKUListSerializer


class HotSKUListView(GenericAPIView):
    serializer_class = HotSKUListSerializer

    def get_queryset(self):
        category_id = self.kwargs.get('category_id')
        skus = SKU.objects.filter(category_id=category_id).order_by('-sales')[:2]

        return skus

    def get(self, request, category_id):
        # 获取对象
        query_set = self.get_queryset()

        # 获取序列化器
        serializer = self.get_serializer(instance=query_set, many=True)

        # 返回数据
        return Response(serializer.data)


class SKUListView(ListAPIView):
    serializer_class = SKUListSerializer
    # 设置过滤后端排序字段
    filter_backends = (filters.OrderingFilter,)
    ordering_fields = ('create_time', 'price', 'sales')

    def get_queryset(self):
        category_id = self.kwargs.get('category_id')
        # 根据分类编号查询数据
        skus = SKU.objects.filter(category_id=category_id)

        return skus


class SKUSearchViewSet(HaystackViewSet):
    """
    SKU搜索
    """

    # 指定数据集
    index_models = [SKU]

    # 序列化器
    serializer_class = SKUIndexSerializer
